﻿namespace Comet.View
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using Comet.Presentation;
    using System.Diagnostics;
    using Comet.Infrastructure;
    
    public partial class DataMembersWindow : Form, IDataMembersView
    {
        DataMembersPresenter presenter;
        public event System.EventHandler ChangesAccepted = delegate { };

        public DataMembersWindow()
        {
            InitializeComponent();
        }

        public DataMembersWindow(DataMembersPresenter presenter) : this()
        {
            if (presenter == null)
            {
                throw new ArgumentNullException("presenter");
            }

            this.presenter = presenter;
            this.presenter.View = this;
        }

        #region IConstructorFromDataMembersView Members

        public void AddDataMember(DataMemberPresenter dataMemberPresenter)
        {
            DataMemberListViewItem listViewItem = new DataMemberListViewItem(dataMemberPresenter);
            
            if (dataMemberPresenter.DataMemberType == DataMemberType.Field)
            {
                listViewItem.Group = this.dataMembersListView.Groups[0];
            }
            else
            {
                listViewItem.Group = this.dataMembersListView.Groups[1];
            }

            this.dataMembersListView.Items.Add(listViewItem);
            this.dataMemberKindColumnHeader.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
            this.typeNameColumnHeader.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
        }

        public void RemoveDataMember(DataMemberPresenter dataMemberPresenter)
        {
            DataMemberListViewItem listViewItem = dataMemberPresenter.View as DataMemberListViewItem;
            Debug.Assert(listViewItem != null, "Type of ListViewItem is not correct");

            this.dataMembersListView.Items.Remove(listViewItem);
        }

        #endregion

        private void RaiseChangesAccepted(EventArgs e)
        {
            ChangesAccepted(this, e);
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            RaiseChangesAccepted(EventArgs.Empty);
            Close();
        }

        private void dataMembersListView_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            DataMemberListViewItem listViewItem = e.Item as DataMemberListViewItem;
            Debug.Assert(listViewItem != null, "Type of ListViewItem is not correct");

            listViewItem.IsSelected = listViewItem.Checked;
        }
    }
}
